package com.xiaobao.coalproperty.module.home.view;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.xiaobao.coalproperty.R;
import com.xiaobao.coalproperty.module.home.model.entity.BlankEntity;
import com.xiaobao.coalproperty.module.home.model.entity.GoodsDetailEntity;
import com.xiaobao.coalproperty.module.home.model.entity.OrderBubmitEntity;
import com.xiaobao.coalproperty.module.user.view.DealPasswordActivity;
import com.xiaobao.coalproperty.module.user.view.OrderPayActivity;
import com.xiaobao.coalproperty.other.adapter.GlideImageLoader;
import com.xiaobao.coalproperty.other.adapter.PropertyAdapter;
import com.xiaobao.coalproperty.other.base.BaseActivity;
import com.xiaobao.coalproperty.other.constant.UrlConstant;
import com.xiaobao.coalproperty.other.util.DialogUtils;
import com.xiaobao.coalproperty.other.util.HttpHelperUtils;
import com.youth.banner.Banner;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;

public class PropertyDetailsActivity extends BaseActivity {

    @BindView(R.id.property_recycler)
    XRecyclerView mXRecyclerView;

    private View headView, footView;
    private Banner mBanner;
    private TextView tvIntro, tvForm, tvName, tvCollect, tvArea, tvAcreage, tvPrice, tvStock, tvDown, tvUp, tvBuyNum, tvNum;
    private WebView webView;
    private ImageView ivCollect;
    private PropertyAdapter mPropertyAdapter;

    private GoodsDetailEntity detailEntity;
    private List<String> imageStrings;
    private String id;

    @Override
    protected int getContentView() {
        return R.layout.activity_property_details;
    }

    @Override
    protected void init(Bundle savedInstanceState) {

        setLeftClickFinish();
        setTitle("资产详情");

        id = getIntent().getStringExtra(getIntent().getAction());


        headView = LayoutInflater.from(this).inflate(R.layout.item_adapter_property_head, null, false);
        footView = LayoutInflater.from(this).inflate(R.layout.item_adapter_property_foot, null, false);

        webView = headView.findViewById(R.id.property_web);
        mBanner = headView.findViewById(R.id.property_banner);
        tvIntro = headView.findViewById(R.id.property_intro);
        tvForm = headView.findViewById(R.id.property_form);
        tvName = headView.findViewById(R.id.property_name);
        tvCollect = headView.findViewById(R.id.property_tv_collect);
        tvArea = headView.findViewById(R.id.property_area);
        tvAcreage = headView.findViewById(R.id.property_acreage);
        tvPrice = headView.findViewById(R.id.property_price);
        tvStock = headView.findViewById(R.id.property_stock);
        ivCollect = headView.findViewById(R.id.property_iv_collect);

        tvDown = footView.findViewById(R.id.property_down);
        tvUp = footView.findViewById(R.id.property_up);
        tvNum = footView.findViewById(R.id.property_tv_buy_num);
        tvBuyNum = footView.findViewById(R.id.property_buy_num);

        tvIntro.setOnClickListener(mOnClickListener);
        tvForm.setOnClickListener(mOnClickListener);
        tvDown.setOnClickListener(mOnClickListener);
        tvUp.setOnClickListener(mOnClickListener);
        ivCollect.setOnClickListener(mOnClickListener);

        mPropertyAdapter = new PropertyAdapter(this);

        mXRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mXRecyclerView.addHeaderView(headView);
        mXRecyclerView.setFootView(footView, mCustomFooterViewCallBack);
        mXRecyclerView.setLoadingListener(mLoadingListener);
        mXRecyclerView.setAdapter(mPropertyAdapter);

        mBanner.setImageLoader(new GlideImageLoader());


        setTextViewBackground(false);

        updateGoodsDetails();
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.property_intro:
                    setTextViewBackground(true);
                    break;
                case R.id.property_form:
                    setTextViewBackground(false);
                    break;
                case R.id.property_down:
                    if (Integer.parseInt(tvBuyNum.getText().toString()) == 1) {
                        return;
                    }
                    tvBuyNum.setText((Integer.parseInt(tvBuyNum.getText().toString()) - 1) + "");
                    break;
                case R.id.property_up:
                    if (detailEntity != null) {
                        if (tvBuyNum.getText().toString().equals(detailEntity.getData().getBuy_num())) {
                            return;
                        }
                        tvBuyNum.setText((Integer.parseInt(tvBuyNum.getText().toString()) + 1) + "");
                    }
                    break;
                case R.id.property_iv_collect:
                    postCollect();
                    break;
            }
        }
    };

    private XRecyclerView.LoadingListener mLoadingListener = new XRecyclerView.LoadingListener() {
        @Override
        public void onRefresh() {
            updateGoodsDetails();
            mXRecyclerView.refreshComplete();
        }

        @Override
        public void onLoadMore() {
            mXRecyclerView.loadMoreComplete();
        }
    };

    private CustomFooterViewCallBack mCustomFooterViewCallBack = new CustomFooterViewCallBack() {
        @Override
        public void onLoadingMore(View yourFooterView) {

        }

        @Override
        public void onLoadMoreComplete(View yourFooterView) {

        }

        @Override
        public void onSetNoMore(View yourFooterView, boolean noMore) {

        }
    };

    public void buyClick(View view) {
        postOrderSubmit();
    }

    private void postCollect() {
        OkHttpUtils.post().url(UrlConstant.URL_GOODS_COLLECTION)
                .params(HttpHelperUtils.getInstance().goodsCollectionParams(id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    BlankEntity entity = new Gson().fromJson(response, BlankEntity.class);
                    if (entity.getCode() == 0) {
                        updateGoodsDetails();
                        return;
                    }
                    showToast(entity.getMsg());
                } catch (Exception e) {
                }
            }
        });
    }

    private void postOrderSubmit() {
        OkHttpUtils.post().url(UrlConstant.URL_ORDER_SUBMIT)
                .params(HttpHelperUtils.getInstance().orderSubmitParams(id, tvNum.getText().toString()))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    OrderBubmitEntity entity = new Gson().fromJson(response, OrderBubmitEntity.class);
                    if (entity.getCode() == 0) {
                        orderSubmitSuccess(entity);
                        return;
                    } else if (entity.getCode() == 2) {
                        setDealPasswork();
                        return;
                    }
                    showToast(entity.getMsg());
                } catch (Exception e) {
                }
            }
        });
    }

    private void orderSubmitSuccess(OrderBubmitEntity entity) {
        Intent intent = new Intent(this, OrderPayActivity.class);
        intent.putExtra("money", entity.getData().getMoney());
        intent.putExtra("oid", entity.getData().getOid());
        startActivity(intent);
    }

    private void setDealPasswork() {
        DialogUtils.createConfirmDialog(this, "提醒", "请先设置交易密码", "确定", "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(PropertyDetailsActivity.this, DealPasswordActivity.class));
            }
        }, null, -1).show();
    }

    private void updateGoodsDetails() {
        OkHttpUtils.post().url(UrlConstant.URL_GOODS_DETAIL)
                .params(HttpHelperUtils.getInstance().goodsDetailParams(id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    GoodsDetailEntity entity = new Gson().fromJson(response, GoodsDetailEntity.class);
                    if (entity.getCode() == 0) {
                        updateGoodsDetailsSuccess(entity);
                        return;
                    }
                    showToast(entity.getMsg());
                } catch (Exception e) {
                }
            }
        });
    }

    private void updateGoodsDetailsSuccess(GoodsDetailEntity entity) {
        this.detailEntity = entity;
        webView.loadUrl(entity.getData().getContent());
        imageStrings = new ArrayList<>();

        for (int i = 0; i < entity.getData().getPics().size(); i++) {
            imageStrings.add(entity.getData().getPics().get(i));
        }

        tvName.setText(entity.getData().getName());
        tvAcreage.setText(entity.getData().getAcreage());
        tvPrice.setText(entity.getData().getPrice());
        tvArea.setText(entity.getData().getArea());
        tvStock.setText(entity.getData().getStock());
        tvNum.setText(entity.getData().getBuy_num());

        if (entity.getData().getIs_collection() == 0) {
            tvCollect.setText("收藏");
            ivCollect.setImageDrawable(getResources().getDrawable(R.drawable.image_widget_not_collect));
        } else {
            tvCollect.setText("已收藏");
            ivCollect.setImageDrawable(getResources().getDrawable(R.drawable.image_widget_collect));
        }

        mPropertyAdapter.setAdapterData(entity.getData().getPeople_info());

        mBanner.setImages(imageStrings);
        mBanner.start();
    }

    private void setTextViewBackground(boolean isIntro) {
        tvIntro.setBackgroundResource(isIntro ? R.color.theme_yellow : R.color.gray);
        tvIntro.setTextColor(isIntro ? getResources().getColor(R.color.white) : getResources().getColor(R.color.theme_yellow));

        tvForm.setBackgroundResource(!isIntro ? R.color.theme_yellow : R.color.gray);
        tvForm.setTextColor(!isIntro ? getResources().getColor(R.color.white) : getResources().getColor(R.color.theme_yellow));

        webView.setVisibility(isIntro ? View.VISIBLE : View.GONE);
        if (isIntro) {
            mPropertyAdapter.setAdapterData(new ArrayList<GoodsDetailEntity.DataBean.PeopleInfoBean>());
        } else {
            if (detailEntity != null) {
                mPropertyAdapter.setAdapterData(detailEntity.getData().getPeople_info());
            }
        }
    }


}
